package com.heima.wemedia.interceptor;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    WmUserMapper wmUserMapper;

    /**
     * preHandle：在业务处理器处理请求之前被调用。预处理，可以进行编码、安全控制、权限校验等处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        log.debug("用户ID："+userId+" 访问："+request.getRequestURL());
        if (userId!=null){
            //TODO: 这里应使用redis缓存用户信息，避免每次请求都查询数据库
            LambdaQueryWrapper<WmUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmUser::getApUserId,userId);
            WmUser wmUser = wmUserMapper.selectOne(lambdaQueryWrapper);
            wmUser.setApUserId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(wmUser);
            log.debug("用户信息："+wmUser);
        }
        return true;
    }

    /**
     * afterCompletion：在DispatcherServlet完全处理完请求后被调用，可用于清理资源等。返回处理（已经渲染了页面）；
     *
     * 这里用于清理ThreadLocal的User对象
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从ThreadLocal中移除User对象
        log.debug("--清理ThreadLocal的User对象--");
        WmThreadLocalUtils.removeUser();
    }

}
